const addressModel = require("../../db/models")["address"];
const responseCode = require("../../config/httpCode");
const router = require("koa-router")({
  prefix: "/api/address"
});

// 获取一个人的所有地址
router.get("/", async ctx => {
  const id = ctx.$$user.id;
  const address = await addressModel.findAll({
    where: { userId: id }
  });
  ctx.body = {
    code: 200,
    data: address
  };
});

// 新增一个地址
router.post("/", async ctx => {
  const id = ctx.$$user.id;
  const address = ctx.request.body;
  address.userId = id;
  const a = await addressModel.create(address);
  ctx.body = {
    code: 200,
    data: a
  };
});

// 修改
router.post("/:id", async ctx => {
  const id = ctx.params.id;
  const a = ctx.request.body;
  const address = await addressModel.update(a, { where: { id } });
  ctx.body = {
    code: 200,
    data: address
  };
});

// 删除
router.delete("/:id", async ctx => {
  const id = ctx.params.id;
  const address = await addressModel.destroy({ where: { id } });
  ctx.body = {
    code: 200,
    data: address
  };
});
module.exports = router;
